#include    "fontmanager.h"
#include    "../common.h"


FontManager* FontManager::fontManagerInstance = 0;

const FontManager* FontManager::getInstance()
{
    return fontManagerInstance;
}

FontManager::FontManager()
{
    m_fontBase = 0;
    m_isFontBuild = false;


    m_glListNumber = 255;
    m_charecterFirst = 0;
    m_fontHeight = -26;

    fontManagerInstance = this;
}

FontManager::~FontManager()
{
    if(fontManagerInstance == this)
    {
        fontManagerInstance = 0;
    }

    if(m_isFontBuild)
    {
        glDeleteLists(m_fontBase,m_glListNumber);
        m_isFontBuild = false;
    }
}

void FontManager::buildFont(HDC hdc)
{
    if(m_isFontBuild)
    {
        return;
    }

    HFONT newFont;
    HFONT oldFont;

    m_fontBase = glGenLists(m_glListNumber);

    newFont = CreateFont(  m_fontHeight, // Height
                            0, // Width
                            0, // Escapement
                            0, // Orientation
                            FW_BOLD, // Weight
                            FALSE, // Italic
                            FALSE, // Underline
                            FALSE, // Strikeout
                            ANSI_CHARSET, // Character Set
                            OUT_TT_PRECIS, // Output Precision
                            CLIP_DEFAULT_PRECIS, // Clipping Precision
                            ANTIALIASED_QUALITY,// Output Quality
                            FF_DONTCARE | DEFAULT_PITCH, // Family/Pitch
                            "Courier New"); // Font Name

    oldFont = (HFONT)SelectObject(hdc, newFont);
    wglUseFontBitmaps(hdc, m_charecterFirst, m_glListNumber , m_fontBase);
    SelectObject(hdc, oldFont);
    DeleteObject(newFont);

    m_isFontBuild = true;
}

void FontManager::drawText(const char* text,int x,int y,float r ,float g,float b)
{
    if(m_isFontBuild == false)
    {
        PERSONAL_DEBUG_LOG("not build font!");
        return;
    }

    if(text == NULL)
    {
        PERSONAL_DEBUG_LOG("render text is null!");
        return;
    }

    glBindTexture(GL_TEXTURE_2D, 0);
    glColor3f(r, g, b);
    glRasterPos2f(x, y);

    glPushAttrib(GL_LIST_BIT);
    glListBase(m_fontBase - m_charecterFirst);
    glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);
    glPopAttrib();

    glColor3f(1.0f, 1.0f, 1.0f);
}
